<?php

namespace Mtt\BlogBundle\Entity\Repository;

use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
use Mtt\BlogBundle\Entity\GeoLocation;

/**
 * GeoLocationRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 *
 * @method GeoLocation|null findOneByIpAddress($ip)
 */
class GeoLocationRepository extends ServiceEntityRepository
{
    /**
     * @param ManagerRegistry $registry
     */
    public function __construct(ManagerRegistry $registry)
    {
        parent::__construct($registry, GeoLocation::class);
    }

    /**
     * @param string $ip
     *
     * @return GeoLocation|null
     */
    public function findOrCreateByIpAddress(string $ip): ?GeoLocation
    {
        $location = null;
        if (filter_var($ip, FILTER_VALIDATE_IP)) {
            $location = $this->findOneByIpAddress($ip);
            if (!$location) {
                $location = new GeoLocation();
                $location
                    ->setIpAddress($ip)
                ;

                $this->getEntityManager()->persist($location);
                $this->getEntityManager()->flush();
            }
        }

        return $location;
    }

    /**
     * @param string $from
     * @param string $to
     *
     * @return int
     */
    public function getLocationsCount(string $from, string $to): int
    {
        $qb = $this->createQueryBuilder('g');
        $qb
            ->select('COUNT(g.id) AS cnt')
            ->andWhere($qb->expr()->gt('g.timeCreated', ':from'))
            ->andWhere($qb->expr()->lte('g.timeCreated', ':to'))
            ->setParameter('from', $from)
            ->setParameter('to', $to)
        ;

        return $qb->getQuery()->getSingleScalarResult();
    }
}
